import { JsonRequest } from '../request'
JsonRequest._session_info = undefined

class Webclient extends JsonRequest {
  constructor(payload) {
    super(payload)
  }

  static async version_info() {
    const url = '/web/webclient/version_info'
    return this.json_call(url, {})
  }
}

class Dataset extends JsonRequest {
  constructor(payload) {
    super(payload)
  }

  static async call_kw(payload) {
    const { model, method, args, kwargs } = payload
    const url = '/web/dataset/call_kw'
    const url2 = `${url}/${model}/${method}`
    return await this.json_call(url2, { model, method, args, kwargs })
  }
}

class Session extends JsonRequest {
  constructor(payload) {
    super(payload)
  }

  static get session_info() {
    return this._session_info
  }

  static get current_company_id() {
    const { user_companies = {} } = this.session_info || {}
    const { current_company } = user_companies
    return current_company
  }

  static get allowed_company_ids() {
    return [this.current_company_id]
  }

  static get user_context() {
    const session_info = this.session_info || {}
    const context = session_info.user_context || {}
    const allowed_company_ids = this.allowed_company_ids
    return { ...context, allowed_company_ids }
  }

  static get context() {
    return this.user_context
  }

  static _session_info_get_after(session_info) {
    const info = { ...session_info }
    const get_user_companies = () => {
      const { server_version_info = [15] } = info
      const ver = server_version_info[0]

      const { user_companies = {} } = info
      if (ver >= 15) return user_companies

      const { current_company, allowed_companies } = user_companies

      return {
        current_company: current_company[0],
        allowed_companies: allowed_companies.reduce((acc, cur) => {
          const [cid, name] = cur
          acc[cid] = { id: cid, name }
          return acc
        }, {})
      }
    }

    const user_companies = get_user_companies()

    return { ...info, user_companies }
  }

  static async authenticate({ db, login, password }) {
    const url = '/web/session/authenticate'
    const payload = { db, login, password }
    const session_info = await this.json_call(url, payload)
    const info = this._session_info_get_after(session_info)
    this._session_info = info
    return session_info
  }
}

class Home extends JsonRequest {
  constructor(payload) {
    super(payload)
  }

  static async tests_mobile() {
    const url = '/web/tests/mobile'
    return await this.http_call(url, {})
  }

  static async benchmarks() {
    const url = '/web/benchmarks'
    return await this.http_call(url, {})
  }
}

const web = Home
web.webclient = Webclient
web.session = Session
web.dataset = Dataset

export default {
  web
}
